#include "fwgui.h"
#include "driver.h"
#include <gba.h>
#include <stdio.h>
#include <string.h>
#include "font.h"
#include "gunship_12_bin.h"
#include "vera_11_bin.h"
#include "dialog.h"
#include "theme.h"

namespace FwGui
{
	Driver::Driver()
		:	framebuffer((uint16_t*)MODE3_FB),
		dialog(NULL),
		needGraphicsInit(false),
		listener(NULL)
	{
		Font::GUNSHIP_12 = new Font(gunship_12_bin);
		Font::VERA_11 = new Font(vera_11_bin);
	}
	
	Driver::~Driver()
	{
		delete Font::GUNSHIP_12;
		delete Font::VERA_11;
	}
	
	void Driver::SetActiveDialog(Dialog* dialog)
	{
		this->dialog = dialog;
		SetListener(dialog);
		if(dialog != NULL)
		{
			needGraphicsInit = true;
			dialog->Repaint();
		}
	}
	
	void Driver::SetListener(InputListener* listener)
	{
		this->listener = listener;
	}
	
	bool Driver::Tick()
	{
		if(listener != NULL) {
			scanKeys();
			
			uint32_t down = keysDown();
			uint32_t up = keysUp();

			for(int i = 0; i < FWGUI_NUM_KEYS; i++) {
				if(down & BIT(i))
					listener->KeyDown((Key)i);
				if(up & BIT(i))
					listener->KeyUp((Key)i);
			}
		}
		
		if(dialog != NULL && dialog->NeedsRepaint())
		{
			if(needGraphicsInit)
			{
				InitGraphics();
				needGraphicsInit = false;
			}

			Graphics* graphics = new Graphics(framebuffer, SCREEN_WIDTH, SCREEN_HEIGHT);
			if(backgroundImage == NULL)
			{
				graphics->SetFillColor(backgroundColor);
				graphics->FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
			}
			else
			{
				graphics->Blit(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, (u16*)backgroundImage);
			}
			dialog->Paint(graphics);
			delete graphics;
			dialog->SetRepaint(false);
		}

		return true;
	}
	
	void Driver::InitGraphics()
	{
		REG_DISPCNT = MODE_3 | BG_ALL_ON;
		REG_BLDCNT = 0;
		REG_BLDY = 0;
	}
}
